import { lazy } from "react";
import routes from "@/config/routes";
import handleName from "./handleName";
import { message } from "antd";
// import FrontendAuth from "./auth/frontendAuth";
// 引入 views 文件夹下所有 vue 文件
const modules = import.meta.glob("@/views/**/index.tsx", {});

// 数组去重方法

function distict(data: any[]) {
  return [...new Set(data)];
}
window.addEventListener("error", function (event) {
  // onerror_statement
  if (event.message.includes("ctor")) {
    message.error("请确保定义了所有的组件");
  }
});

export const filterRoute = (data: any[], i = 1, pathName = "") => {
  const routers = routes as any;
  const router = distict(data.map((item) => item[i])).map((it) => {
    const { comPath, key, routePath } = handleName({ pathName, i, it });

    const Com = function () {
      try {
        return lazy(modules[comPath] as any);
      } catch (error) {
        message.error("...");
        console.log("errr", error);
      }
    };
    const Comm = Com();
    let level = i + 1;

    const route: any = {
      path: routePath,
      element: <Comm />,
      meta: { ...routers[key] },
    };
    const children = data.filter((rr) => rr[i] == it && rr[level] != null);

    if (children.length) {
      delete route.element;
      route.redirect = routePath + "/" + children[0][children[0].length - 1];

      route.children = filterRoute(children, level, route.path);
    }
    return route;
  });
  return router;
};
